package chapter04.exercise;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * 买票类
 */
@Slf4j
public class ExerciseSell {

    public static void main(String[] args) {
        TicketWindow ticketWindow=new TicketWindow(5000);
        List<Thread> list=new ArrayList<>();
        // 用来存储卖出去多少张票
        List<Integer> sellCount=new Vector<>();
        for(int i=0;i<2000;i++){
            Thread t = new Thread(() -> {
                int count = ticketWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        list.forEach((t)->{
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 卖出去的票求和
        log.debug("selled count:{}",sellCount.stream().mapToInt((c->c)).sum());
        // 剩余票数
        log.debug("ramainder count:{}",ticketWindow.getCount());

    }
    static Random random=new Random();
    public static int randomAmount(){
        return random.nextInt(5)+1;

    }
}
class TicketWindow{
    private int count;
    public TicketWindow(int count){
        this.count=count;
    }
    public int getCount(){
        return count;
    }
    public synchronized int sell(int amount){
        if (this.count>=amount){
            this.count-=amount;
            return amount;
        }else {
            return 0;
        }
    }
}
